package com.maxjay.system.menu.parser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.maxjay.system.constant.YesNoConstant;
import com.maxjay.system.menu.model.MenuTreeNode;
import com.maxjay.system.service.BaseServiceJdbc;

@Component("menuTreeParser")
public class DatabaseTreeParser extends BaseServiceJdbc implements MenuTreeParser {
	
	private static final Logger LOG = Logger.getLogger(DatabaseTreeParser.class);

	private MenuTreeNode root = null;
	
	@Override
	public void parse(List<String> menuNodeIds) {
		Map<String, MenuTreeNode> menuTreeMap = getTreeNodeMap();
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, MenuTreeNode> entry : menuTreeMap.entrySet()) {
			String menuNodeId = entry.getKey();
			if (menuNodeIds!=null && !menuNodeIds.contains(menuNodeId)) {
				continue;
			}
			sb.append(menuNodeId).append(",");
			MenuTreeNode menuTreeNode = menuTreeMap.get(menuNodeId);
			String parentId = menuTreeNode.getParentId();
			if (StringUtils.isBlank(parentId)) {
				root = menuTreeNode;
			} else {
				MenuTreeNode parentNode = menuTreeMap.get(parentId);
				menuTreeNode.setParent(parentNode);
			}
		}
		LOG.info("取得的用户菜单权限为：" + sb.toString());
	}

	private Map<String, MenuTreeNode> getTreeNodeMap() {
		String qryMenuSql = "select * from T_SYS_MENU t";
		List<Map<String, Object>> menus = this.getSimpleJdbcTemplate().queryForList(qryMenuSql);
		Map<String, MenuTreeNode> menuTreeMap = new HashMap<String, MenuTreeNode>();
		for (Map<String, Object> map : menus) {
			String id = (String)map.get("OBJ_ID");
			String text = (String)map.get("NAME");
			String url = (String)map.get("URL");
			String parentId = (String)map.get("PARENT_ID");
			MenuTreeNode menuTreeNode = new MenuTreeNode(id, text, url, parentId);
			if (YesNoConstant.YES.equals(map.get("IS_LEAF"))) {
				menuTreeNode.setIsLeaf(true);
			}
			menuTreeNode.setType((String)map.get("TYPE"));
			menuTreeMap.put(id, menuTreeNode);
		}
		LOG.debug("加载的菜单信息为：" + menuTreeMap);
		return menuTreeMap;
	}

	@Override
	public MenuTreeNode getMenuTree(List<String> menuNodeIds) {
		if (root == null) {
			parse(menuNodeIds);
		}
		return root;
	}
	
}